import { useState } from 'react';
import { ProFormSelect } from '@ant-design/pro-components';

import ProTable from '@/components/ProTable';
import request from '@/utils/request';

import { complexityColumns, fileDetailsColumns, formatUrl } from './constants';

const searchOptions = [
  {
    label: '全部',
    value: 'all',
  },
  {
    label: '无需',
    value: 'no',
  },
  {
    label: '建议重构',
    value: 'medium',
  },
  {
    label: '强烈建议重构',
    value: 'bad',
  },
];

const searchType = {
  all: 0,
  no: [0, 50],
  medium: [50, 70],
  bad: 70,
};

const TrendTable = ({ url, startDate, endDate }) => {
  const [searchKey, setSearchKey] = useState('all');

  const renderExpandTable = ({ url, file_path }) => {
    return (
      <ProTable
        params={{ start_date: startDate, end_date: endDate }}
        request={async (params) => {
          const res = await request('/api/file_details', {
            method: 'POST',
            data: { file_path, ...params },
          });
          return {
            data: res.data,
            success: res.success,
            total: res.total,
          };
        }}
        search={false}
        columns={[
          {
            title: '位置',
            dataIndex: 'func_loc',
            tip: '函数所在位置',
            render: (v, { file_path }) => {
              const { targetPath } = formatUrl(v, url);
              return (
                <a
                  href={targetPath.replace('[', '#L')}
                  target="_blank"
                  rel="noreferrer"
                >
                  {v.replace(file_path, '')}
                </a>
              );
            },
          },
          ...fileDetailsColumns,
        ]}
      />
    );
  };

  return (
    <ProTable
      params={{
        url,
        searchRange: searchType[searchKey],
        start_date: startDate,
        end_date: endDate,
      }}
      request={async (params) => {
        const res = await request('/api/complexity', {
          method: 'POST',
          data: params,
        });
        return {
          data: res.data,
          success: res.success,
          total: res.total,
        };
      }}
      toolBarRender={() => {
        return [
          <ProFormSelect
            key="search"
            options={searchOptions}
            value={searchKey}
            fieldProps={{ allowClear: false }}
            onChange={setSearchKey}
          />,
        ];
      }}
      rowKey="id"
      expandable={{
        expandedRowRender: renderExpandTable,
      }}
      search={false}
      columns={complexityColumns}
    />
  );
};

export default TrendTable;
